_T.Ui.GridPanel = {};

_T.Ui.GridPanel.Column = function (el, index) {
	
    var _this = this;

    this.el = el;

    this.index = index;

    this.get = function (name) {
        return this.el.getAttribute(name);
    };

    this.cls = function () {
        var cls = '';
        if (this.index > 3) {
            cls = 'hidden-xs';
        }
        if (this.index > 6) {
            cls = 'hidden-sm';
        }
        return cls;
    };

    //获取头列
    this.header = function () {
    	var th = $("<th/>");
        if (this.get('type') == 'checkbox') {
        	var checkbox = $("<input type='checkbox'>") ;
        	checkbox.appendTo(th);
        }else if(this.get('type') == 'radio') {
        	th.append("&nbsp;");
        }else {
        	th.append( this.get('header')) ;
        }
        if(this.get("order") == 'true' ){
        	var odiv = $('<div class="sort sort-gray pull-right"></div></th>');
        	odiv.appendTo(th);
        	th.css({'cursor': 'pointer'});
        }
        if(this.get("width")){
            th.css('width',this.get("width"));
        }
        th.css("text-align","center");
        th.addClass(this.cls());
        return th ;
    };
    
    //添加空白列
    this.blankCell = function () {
    	var td = $("<td />").addClass(this.cls());
    	if(this.get('align') ){
    		td.attr("align",this.get('align'));
    	}
    	td.append("&nbsp;");
        return td ;
    };

    this.format = function (data) {
        if (data == null) {
            return '&nbsp;';
        }
        var value = this.get('value');
        for (var key in data) {
            var re = new RegExp("\\$\\(" + key + "\\)", "ig");
            value = value.replace(re, data[key] == null ? '--' : data[key]);
        }
        return value;
    };

    this.column = function () {
        var value = this.get('value');
        return value.replace(/\$\(/ig, '').replace(/\)/, '');
    };
    
    this.html = function (data, rowIndex, colIndex) {
        var value = this.format(data);
        if (typeof (this[this.get('type')]) == 'function') {
            value = this[this.get('type')](value, data, rowIndex, colIndex);
        }
        return value;
    };

    //
    this.radio = function (value, data, rowIndex, colIndex) {
        if (data == null) {
            return '&nbsp;';
        }
        return '<input type="radio" value="' + value + '" name="'+this.get("value")+'">';
    };

    //
    this.checkbox = function (value, data, rowIndex, colIndex) {
        if (data == null) {
            return '&nbsp;';
        }
        return '<input type="checkbox" value="' + value +'">';
    };
};

_T.Ui.GRID = _T.Ui.Grid = _T.Ui.GridPanel.Grid = function (el) {

    var _this = this;

    this.el = el;

    this.get = function (name) {
        return this.el.getAttribute(name);
    };

    //当前页数
    this.index = 0;

    //每页
    this.limit = this.get('pageSize') ? parseInt(this.get('pageSize')) : 10;

    //总页数
    this.size = 0;
    
    //排序列
    this.orderIndex = null;

    //排序列
    this.orderby = null;

    //排序方向
    this.order = null;

    this.columns = [];

    this.params = {};
    
    this.init = function () {

        this.initModel();

        this.create();

        this.load();
        
        this.initEvent();
    };

    this.initModel = function () {
        $(this.el.childNodes).each(function (idx, child) {
        	if (child.tagName && child.tagName.toUpperCase() == 'COLUMN') {
                _this.columns.push(new _T.Ui.GridPanel.Column(child, _this.columns.length));
            }
        });
        $(this.el).hide();
    };

    this.create = function () {
    	
    	var id = _this.get('tid');
    	
    	//调整宽度
    	var tdiv = $("<div></div>") ;
    	tdiv.css({"overflow":"auto", 'padding-right':'15px'});
    	
    	//表头
    	var thead = $("<table class='table table-striped table-bordered table-hover'><thead><tr></tr></thead></table>");
    	 $(_this.columns).each(function (idx, column) {
    		 var th = column.header();
    		 th.appendTo(thead.find("tr"));
         });
    	 thead.attr("id",id+"_header");
    	 thead.appendTo(tdiv);
    	 tdiv .appendTo($(_this.el).parent());
    	 
    	//固定高度
    	var ddiv = $("<div></div>") ;
    	ddiv.css({'height':_this.get("height"),"overflow-y":"scroll",'position':'relative'});
    	
    	//表体
    	var tbody = $('<table class="table table-striped table-bordered table-hover"><tbody><tr></tr></tbody></table>');
    	tbody.css({'padding-right':'0px'});
    	tbody.attr("id",id);
    	tbody.appendTo(ddiv);
    	ddiv .appendTo($(_this.el).parent());
    	
     	//统一宽度
    	thead.find("th").each(function(idx,el){
      		 var th = $(el);
      		 var htd = $("<td/>",{height:'0px',width:th.outerWidth()+"px"});
      		 htd.css({'padding': ' 0 0px 0 0px ' });
      		 htd.appendTo(tbody.find("tbody > tr"));
      	});
    	
    	//table变化时调整列宽度
    	thead.resize(function(){
    		thead.find("th").each(function(idx,el){
    			 var th = $(el);
    			 var tds = tbody.find("tbody > tr").eq(0).find("td").eq(idx);
    			 tds.css({width:th.outerWidth()});
    		});
    	});
    	
    	var pdiv = $("<div class='widget-foot'></div>");
    	pdiv.attr("id",id+'_page');
    	pdiv.appendTo($(_this.el).parent());
    	
    	var zdiv = $('<div class="pagination pull-right" style="margin: 0px 5px -1px 5px ;"></div>');
    	var select = $('<select><option>10</option><option>20</option><option>30</option></select>');
    	select.css({height:'30px',width:'50px','border':'1px solid #ddd'});
    	select.appendTo(zdiv);
    	zdiv.appendTo(pdiv);
    	
    	var plul = $('<ul class="pagination pull-right" style="margin: -1px;"></ul>');
    	plul.appendTo(pdiv);
    	
    	 var nli = $('<li onclick="_T.get(\'' + id + '\').to(\'next\')"><a href="#">></a></li>');
      	var eli = $('<li onclick="_T.get(\'' + id + '\').to(\'last\')"><a href="#">&raquo;</a></li>');
      	nli.appendTo(plul);
      	eli.appendTo(plul);
    	
    	var zdiv = $('<div class="pagination pull-right" style="margin: 0px 5px 0px 5px ;">第 <input/> 页</div>');
    	zdiv.find("input").css({height:'30px',width:'40px','border':'1px solid #ddd','text-align':'center'});
    	zdiv.appendTo(pdiv);
    	
    	var pnul = $('<ul class="pagination pull-right" style="margin: -1px;"></ul>');
    	pnul.appendTo(pdiv);
    	
        var fli = $('<li onclick="_T.get(\'' + id + '\').to(\'first\')"><a href="#">&laquo;</a></li>');
        var lli = $('<li onclick="_T.get(\'' + id + '\').to(\'previous\')"><a href="#"><</a></li>');
    	fli.appendTo(pnul);
    	lli.appendTo(pnul);
        
    	
    	var pspan = $('<p style="margin: 8px;">第<span>0</span>/<span>0</span>页，共<span>0</span>条</p>');
    	pspan.appendTo(pdiv);
    };

    this.load = function (params) {
        _this.params = params || {};
        _this.params['pageNum'] = _this.index;
        _this.params['totalCount'] = _this.size;
        _this.params['pageSize'] = _this.limit;
        _this.params['orderby'] = _this.orderby;
        _this.params['order'] = _this.order;
        //排序列为空的清空下 不传入order
        if (_this.orderby == null || _this.orderby == '') {
            delete _this.params['orderby'];
            delete _this.params['order'];
        }
        var reader = new _T.Ajax({url:_this.get('url'), params:_this.params});
        this.data = {info:{success:false, msg:'', totalCount:0}, result:[]};
        reader.load(function (data) {
            if (data.result && data.result.length > 1) {
                _this.data = data;
            }
            _this.fill();
            _this.markOrder();
           _this.page();
           _this.cancelEvent();
        }, this);
    };
    
    //////////////////////////////////////////////////////////////////////////////////////
    //注册事件
    this.initEvent = function () {
    	  var id = _this.get('tid');
          //标头多选框事件
          var ths = $("#" + id + "_header").find("thead > tr > th");
          
         //排序
          ths.each(function (idx, th) {
        	  $(th).on('click',function(){
            	  var column = _this.columns[$(th).index()];
                  if (column.get('order') == 'true') {
                      _this.orderIndex = $(th).index();
                      _this.orderby = column.column();
                      _this.order = $(th).find('.sort').hasClass('sort-gray') || $(th).find('.sort').hasClass('sort-desc') ? 'asc' : 'desc';
                      _this.reload();
                  }
        	  });
        	  
        	  //多选和单选
              $(th).find('input:checkbox,input:radio').on('click', function (event) {
                  var boxs = $("#" + id).find("tbody > tr").find("td:eq(" + $(th).index() + ") input:checkbox,input:radio");
                  for(var i = 0 ; i<boxs.length ; i++){
                	  boxs[i].checked = this.checked?false:true ;
                	  $(boxs[i]).parent().parent().click();
                  }
              });
          });
         
       //分页事件
         $("#" + id +"_page").find('input:text').on('keydown', function (event) {
             if (event.keyCode == 13) {
                 _this.to($(this).val());
             }
         });
         //每页事件
         $("#" + id +"_page").find('select').on('change', function (event) {
             _this.setPageSize($(this).val());
         });
    };
    
    //
    this.cancelEvent = function () {
        var id = _this.get('tid');
        $("#" + id).find("tbody > tr > td input:checkbox,input:radio").on('click', function (event) {
        	$(this).parent().parent().click();
        });
    };
    
    //填充数据
    this.fill = function () {
        var tby = $("#" + _this.get('tid')).find("tbody");
        for (var i = 0; i < _this.limit; i++) {
            var tr = tby.find("tr:eq(" + (i+1) + ")");
            if (tr.size() == 0) {
               _this.addRow();
               tr = tby.find("tr:eq(" +  (i+1)  + ")");
            }
            var data = _this.data.result[i] || null;
            $(_this.columns).each(function (idx, column) {
                var value = column.html(data,  (i+1) , idx);
                var td = tr.find("td:eq(" + idx + ")");
                td.empty().append(value);
            });
            tr.removeClass("success");
           // tr.find("input:checkbox,input:radio")[0].checked = false;
        }
        
        //数据小于条数删除多于行
        tby.find("tr").each(function(idx,el){
        	if(idx <=  _this.data.result.length){
        		return ;
        	}
        	$(this).remove();
        });
        
        //分页清除数据
        _this.selection = null;
    };
    
    this.markOrder = function () {
        if (_this.orderby == null || _this.orderby == '') {
            return;
        }
        var headerId = _this.get('tid') + "_header" ;
        var ths = $("#" + headerId).find("thead > tr > th");
        ths.find('.sort').addClass('sort-gray').removeClass('sort-asc').removeClass('sort-desc');
        var th = $("#" +headerId).find("thead > tr > th:eq(" + _this.orderIndex + ")");
        th.find('.sort').removeClass('sort-gray').addClass("sort-" + this.order);
    };

    //动态添加行
    this.addRow = function () {
    	 var id = _this.get('tid');
    	 
        var tby = $("#" + id).find("tbody");
        var tr = $('<tr/>');
        $(_this.columns).each(function (idx, column) {
        	column.blankCell().appendTo(tr);
        });
        tr.appendTo(tby);
        
        //选择样式
        tr.on('click', function () {
        	 var selectes = $(this).find("input:checkbox,input:radio");
        	 _this.selection = _this.data.result[$(this).index()-1];
            if(selectes.is(":radio")){
            	$(this).parent().find("tr").removeClass('success');
            }
            if(selectes[0].checked){
            	   $(this).removeClass('success');
            	   selectes[0].checked = false ;
            	   _this.selection = null ;
            }else{
            	 $(this).removeClass('success').addClass('success');
          	    selectes[0].checked = true ;
            }
        });
        
        return  tr ;
    };
    
    //分页
    this.page = function () {
    	//当前选中的页数
        _this.index = _this.data.pageNum ;
        //总的页数
        var _count  = _this.data.totalPage ;
        //总的条数
        _this.size = _this.data.totalCount ;
        
        if( _this.index > _count ){
        	_this.index = _count  ;
        }
        
        var page = $("#" + _this.get('tid') + "_page");
        page.find('p > span:eq(0)').empty().html(_this.index);
        page.find('p > span:eq(1)').empty().html(_count );
        page.find('p > span:eq(2)').empty().html(_this.data.totalCount);
     
        page.find('li:eq(0)').removeClass('disabled');
        page.find('li:eq(1)').removeClass('disabled');
        page.find('input:text').val(_this.index);
        page.find('li:eq(2)').removeClass('disabled');
        page.find('li:eq(3)').removeClass('disabled');
        if (_this.index == _count) {
            page.find('li:eq(0)').addClass('disabled');
            page.find('li:eq(1)').addClass('disabled');
        }
        if (_this.index == 1) {
            page.find('li:eq(2)').addClass('disabled');
            page.find('li:eq(3)').addClass('disabled');
        }
    };

    //分页获取数据
    this.to = function (param) {
        if (typeof param == 'string') {
            if (param === 'first') {
            	_this.index = 1 ;
            }else if (param === 'last') {
            	_this.index = _this.data.totalPage ;
            }else if (param === 'previous') {
            	_this.index  -= 1 ;
            }else if (param === 'next') {
            	_this.index  += 1 ;
            }else{
            	_this.index = param ;
            }
        }    	
         _this.load(_this.params);
    };

    //设置每页大小
    this.setPageSize = function (pageSize) {
        pageSize = parseInt(pageSize);
        if (pageSize != 'NaN') {
            this.limit = pageSize;
            _this.load(_this.params);
        }
    };
    
    //////////////////////////////////////////////////////////////////////////////////////
    //获取多选checkbox值
    this.getSelectValues = function () {
        var id = _this.get('tid'), values = [];
        var td = $("#" + id).find("tbody > tr > td");
        td.find('input:checkbox:checked').each(function (idx, checkbox) {
            values.push($(checkbox).val());
        });
        return values.join(',');
    };

    //////////////////////////////////////////////////////////////////////////////////////
    //获取选择的行数据
    this.getSelection = function () {
        return this.selection;
    };
    
    this.reload = function () {
        _this.load(_this.params);
    };
    
    this.init();
};
